package fm.controller;

import com.alibaba.fastjson.JSON;
import fm.api.yunpian.FlowApi;
import fm.api.yunpian.FlowBuyMessage;
import fm.api.yunpian.SmsApi;
import fm.entity.Activity;
import fm.entity.Flow;
import fm.entity.RecorderParticipation;
import fm.entityEnum.ExchangeStatus;
import fm.exception.BizException;
import fm.service.ActivityService;
import fm.service.RecorderParticipationService;
import fm.util.CommonUtils;
import fm.web.MediaTypes;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.List;

/**
 * class name： fm.controller.ExchangeController
 * author： CM
 * create time： 2016/3/10.
 */
@Controller
@RequestMapping("/exchange")
public class ExchangeController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExchangeController.class);
    @Autowired
    private RecorderParticipationService recorderParticipationService;
    @Autowired
    private ActivityService activityService;

    @ResponseBody
    @RequestMapping(value = "/flow/{id}", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public String exchange(ModelMap modelMap,
                           @PathVariable(value = "id") Long id,
                           @RequestParam String tel) throws Exception {
        try {
            if (CommonUtils.isEmpty(tel)) {
                throw new BizException("请提交正确的手机号码！");
            }
            Activity activity = activityService.getById(id);
            if (CommonUtils.isEmpty(activity)) {
                throw new BizException("未找到对应的活动所下发的流量兑换券！");
            }
            //查找手机号码对应的用户和中奖纪录
            List<RecorderParticipation> recorders = recorderParticipationService.getRecorderByPhoneAndActivity(tel, activity);
            if (CollectionUtils.isEmpty(recorders)) {
                throw new BizException("该手机号码尚未参与活动哦！");
            } else {
                //多条记录 默认取第一条
                RecorderParticipation recorder = recorders.get(0);
                //判断兑奖状态
                long currentTime = System.currentTimeMillis() / 1000;
                long creatTime = recorder.getCreateTime().getTime() / 1000;
                long restTime = 3600 + (creatTime - currentTime);
                if (!ExchangeStatus.NOEXCHANGE.equals(recorder.getExchangeStatus())) {
                    //不是未兑奖状态
                    String msg = "";
                    switch (recorder.getExchangeStatus()) {
                        case EXCHANGED:
                            msg = "该手机号码的流量券已经兑换过了！";
                            break;
                        case EXCHANGING:
                            msg = "该手机号码的流量券已经在兑换中，请耐心等候流量送达！";
                            break;
                        case EXPIRED:
                            msg = "该手机号码的流量券已经失效了！";
                            break;
                        default:
                            msg = "流量券兑换失败!";
                    }
                    throw new BizException(msg);
                } else {
                    //发起兑奖流程
                    if (restTime < 0) {
                        recorder.setExchangeStatus(ExchangeStatus.EXPIRED);
                        recorderParticipationService.updateRecorder(recorder);
                        throw new BizException("该手机号码的流量券已经失效了！");
                    }
                    //更新兑换记录
                    recorder.setExchangeStatus(ExchangeStatus.EXCHANGING);
                    recorder.setExchangeTime(new Timestamp(System.currentTimeMillis()));
                    recorderParticipationService.updateRecorder(recorder);
                    Flow flow = recorder.getFlow();
                    if (CommonUtils.isEmpty(flow)) {
                        throw new BizException("这个号码没有未兑换的流量券哦！");
                    }
                    LOGGER.info("phone:{} exchange flow :{}", tel, JSON.toJSONString(flow));
                    FlowBuyMessage msg = FlowApi.buyFlow(recorder.getTelephone(), flow.getSn(), "");

                    if (FlowBuyMessage.SUCCESS.equals(msg.getCode())) {
                        //订购成功
                        modelMap.put("msg", "兑换成功,流量将在两个工作日内送达，请注意短信提醒!");
                        modelMap.put("flowSize", recorder.getFlow().getCapacity());
                        recorder.setExchangeStatus(ExchangeStatus.EXCHANGED);
                        recorderParticipationService.updateRecorder(recorder);

                        try {
                            //发送短信
                            SmsApi.sendSms(tel, "【CM工作室】由巅峰支付提供的流量营销平台，为您充值了" + flow.getCapacity() + "M流量，请注意查收！");
                        } catch (Exception ex) {
                            LOGGER.error("tel:{},exchange flow success! send sms occur error:", tel, ex);
                        }
                        this.success(modelMap);
                    } else {
                        //请求成功，但订购失败
                        recorder.setExchangeStatus(ExchangeStatus.EXCHANGED);
                        recorderParticipationService.updateRecorder(recorder);
                        throw new BizException("为您订购流量失败了，请联系我们！");
                    }

                }
            }
        } catch (BizException ex) {
            LOGGER.error("exchange occur error:", ex);
            this.failed(modelMap, ex);
        } catch (Exception ex) {
            LOGGER.error("exchange occur error:", ex);
            this.failed(modelMap, "为您订购流量失败了，请联系我们！");
        }
        return JSON.toJSONString(modelMap);
    }
}
